package com.crdeng.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crdeng.Utils.MD5Util;
import com.crdeng.handler.BusinessException;
import com.crdeng.response.Result;
import com.crdeng.response.ResultCode;
import com.crdeng.system.entity.Role;
import com.crdeng.system.entity.User;
import com.crdeng.system.service.RoleService;
import com.crdeng.system.service.UserService;
import com.crdeng.system.vo.UserInfo;
import com.crdeng.system.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author crdeng
 * @since 2020-11-16
 */

@Api(value = "用户模块", tags = "用户功能模块")
@RestController
@RequestMapping("/user")
//@CrossOrigin //解决跨域问题
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    /**
     * 分页查询所有用户
     *
     * @param current 当前页
     * @param size    每页显示条数
     * @return
     */
    @ApiOperation(value = "用户列表", notes = "分页查询所有用户")
    @GetMapping("/findUserList")
    public Result findUserList(@RequestParam(defaultValue = "1") Integer current,
                               @RequestParam(defaultValue = "6") Integer size) {
        Page<User> page = new Page<>(current, size);
        Page<User> userPage = userService.page(page);
        long total = userPage.getTotal();
        List<User> records = userPage.getRecords();

        return Result.ok().data("userList", records).data("total", total);
    }

    /**
     * 分页查询所有用户
     *
     * @param current 当前页
     * @param size    每页显示条数
     * @return
     */
    @ApiOperation(value = "条件用户列表", notes = "分页条件查询所有用户")
    @PostMapping("/findUserPage")
    public Result findUserPage(@RequestParam(defaultValue = "1") Integer current,
                               @RequestParam(defaultValue = "6") Integer size,
                               @RequestBody UserVO UserVO) {
        Page<User> page = new Page<>(current, size);
        QueryWrapper<User> warpper = getWarpper(UserVO);
        warpper.eq("deleted", 0);
        IPage<User> userPage = userService.findUserPage(page, warpper);
        long total = userPage.getTotal();
        List<User> records = userPage.getRecords();


        return Result.ok().data("userList", records).data("total", total);
    }

    private QueryWrapper<User> getWarpper(UserVO userVO) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if (userVO != null) {
            if (!StringUtils.isEmpty(userVO.getDepartmentId())) {
                userQueryWrapper.eq("department_id", userVO.getDepartmentId());
            }
            if (!StringUtils.isEmpty(userVO.getEmail())) {
                userQueryWrapper.eq("email", userVO.getEmail());
            }
            if (!StringUtils.isEmpty(userVO.getNickname())) {
                userQueryWrapper.eq("nickname", userVO.getNickname());
            }
            if (!StringUtils.isEmpty(userVO.getSex())) {
                userQueryWrapper.eq("sex", userVO.getSex());
            }
            if (!StringUtils.isEmpty(userVO.getUsername())) {
                userQueryWrapper.eq("username", userVO.getUsername());
            }
        }
        return userQueryWrapper;
    }


    @ApiOperation(value = "查询用户信息", notes = "根据用户ID查询用户信息")
    @GetMapping("/getUserById")
    public Result getUserById(@RequestParam Long id) {
        UserInfo userInfo = userService.getUserById(id);
        if (StringUtils.isEmpty(userInfo)) {
            throw new BusinessException(ResultCode.USER_ACCOUNT_DISABLE.getCode(), ResultCode.USER_ACCOUNT_DISABLE.getMessage());

        }

        return Result.ok().data("user", userInfo);
    }

    @ApiOperation(value = "添加用户", notes = "添加用户")
    @PostMapping("/addUser")
    public Result addUser(@Validated @RequestBody User user) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", user.getUsername());
        User userInfo = userService.getOne(userQueryWrapper);
        //存在就返回
        if (userInfo != null) {
            throw new BusinessException(ResultCode.USER_ACCOUNT_ALREADY_EXIST.getCode(), ResultCode.USER_ACCOUNT_ALREADY_EXIST.getMessage());
        }
        user.setId(null);
        Date date = new Date();
        user.setCreateTime(date);
        user.setModifiedTime(date);
        user.setStatus(1);
        user.setSalt(MD5Util.getSalt());
        user.setPassword(MD5Util.encode(user.getPassword()));
        user.setDeleted(0);
        boolean flag = userService.save(user);
        if (!flag) {
            return Result.error().message("添加失败");
        }
        return Result.ok().message("添加成功");
    }


    @ApiOperation(value = "删除用户", notes = "根据ID删除用户")
    @DeleteMapping("/deleteUser")
    public Result deleteUser(@RequestParam Long id) {

        userService.deleteUserById(id);
        return Result.ok();
    }


    @ApiOperation(value = "编辑用户", notes = "根据ID编辑用户")
    @PutMapping("/editUser")
    public   Result editUser(@RequestBody User user){

        userService.editUser(user);
        return Result.ok();
    }


    @ApiOperation(value = "用户拥有和未拥有的权限" ,notes = "查询用户拥有和未拥有的权限")
    @GetMapping("/getRoleByUserId")
    public Result getRoleByUserId(@RequestParam Long id){
        List<Integer> userRoleIdList = userService.getROleList(id);
        List<Role> roleList = roleService.list();
        return Result.ok().data("userRoleIdList",userRoleIdList).data("roleList",roleList);
    }


    @ApiOperation(value = "分配角色" ,notes = "给用户分配角色")
    @PutMapping("/saveRoleByUserId")
    public Result saveRoleByUserId(@RequestParam Long id,@RequestBody List<Integer> rolsId){
          userService.saveRoleByUserId(id,rolsId);
        return Result.ok();
    }




}




